package com.redare.dev.smart.generator.workbench.interceptor;

import com.google.common.collect.ImmutableMap;
import com.redare.devframework.common.pojo.CommonResult;
import com.redare.devframework.common.spring.interceptor.BaseInterceptor;
import com.redare.devframework.common.utils.JsonUtils;
import com.redare.devframework.webplatform.sdk.core.pojo.User;
import com.redare.devframework.webplatform.workbench.utils.WorkbenchUtil;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author yangqy on 2021/11/5
 * @date 2021/11/5 上午10:36
 */
public class GeneratorWorkbenchInterceptor extends BaseInterceptor {

    private int needLoginErrorCode = 1000;

    private boolean isAjax(HttpServletRequest request) {
        String xmlRequest = request.getHeader("x-requested-with");
        return StringUtils.isNotBlank(xmlRequest) && ("XMLHttpRequest".equalsIgnoreCase(xmlRequest) || "FetchRequest".equalsIgnoreCase(xmlRequest));
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws UnsupportedEncodingException {
        String uriRootPath = WorkbenchUtil.getUriRootPath(request);
        String uriPath = request.getRequestURI().replace(uriRootPath, "");
        if (!uriPath.startsWith("/api/_generator_api/") && !uriPath.startsWith("/_generator")
                &&!uriPath.startsWith("/api/_rootlab_api/")&&!uriPath.startsWith("/api/_rootlab/")
                && !uriPath.startsWith("/login") && !uriPath.startsWith("/api/_js/") && !uriPath.startsWith("/api/login") && !uriPath.startsWith("/api/loginOut")) {
            User user = (User)request.getSession().getAttribute("WEB_WORKBENCH_LOGIN_USER_INFO");
            if (user != null) {
                return true;
            } else {
                String redirectUrl = String.format("%s/login", uriRootPath);
                if (this.isAjax(request)) {
                    response.addHeader("error", "redirect");
                    response.addHeader("redirectUrl", redirectUrl);
                    this.writerHtmlToBody(response, JsonUtils.toJson(CommonResult.returnWrapper(needLoginErrorCode, "请先登录", ImmutableMap.of("loginUrl", redirectUrl))));
                } else {
                    String backUrl = request.getHeader("X-RequestURL");
                    String query;
                    if (StringUtils.isBlank(backUrl)) {
                        backUrl = request.getRequestURL().toString();
                        query = request.getQueryString();
                        if (StringUtils.isNotBlank(query)) {
                            backUrl = String.format("%s?%s", backUrl, query);
                        }
                    }

                    backUrl = URLEncoder.encode(backUrl, "UTF-8");
                    redirectUrl = String.format("%s?backUrl=%s", redirectUrl, backUrl);
                    query = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"><HTML>  <HEAD><script>parent.window.location.href='" + redirectUrl + "';</script></HEAD>  <BODY>  </BODY></HTML>";
                    this.writerHtmlToBody(response, query);
                }

                return false;
            }
        } else {
            return true;
        }
    }



}
